package com.example.kcp.output;

import com.example.kcp.enums.CommandCode;
import com.example.kcp.message.ProtocolMessage;
import com.example.kcp.utils.BytesUtil;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.datagram.DatagramSocket;

import java.nio.charset.StandardCharsets;

/**
 * @author "陈凯航"
 * @date 2024/10/7
 * @mail "mengxingcn@aliyun.com"
 */
public class ReadSingleValueBuilder extends BaseBuilder<ReadSingleValueBuilder> {
    public ReadSingleValueBuilder() {
        this.commandCode = CommandCode.READ_SINGLE_VARIABLE_VALUE;
        this.authorizationCode=new byte[16];
    }

    private String valName;

    public ReadSingleValueBuilder valName(String valName) {
        byte[] bytes = valName.getBytes(StandardCharsets.US_ASCII);
        if (bytes.length > 16) throw new IllegalArgumentException("The parameter length cannot exceed 16 bytes");
        this.valName=valName;
        return this;
    }

    @Override
    protected byte[] buildData() {
        byte[] bytes = this.valName.getBytes(StandardCharsets.US_ASCII);
        return BytesUtil.alignTo16(bytes);
    }

    @Override
    protected short buildDataLength() {
        return 16;
    }

    public static void main(String[] args) {
        ReadSingleValueBuilder readSingleValueBuilder = new ReadSingleValueBuilder();
        ProtocolMessage di0001 = readSingleValueBuilder.valName("DI0001").build();
        Vertx vertx = Vertx.vertx();
        DatagramSocket datagramSocket = vertx.createDatagramSocket();
        datagramSocket.send(Buffer.buffer(di0001.toByteArray()),1234,"127.0.0.1");
        datagramSocket.close();
        vertx.close();
    }
}